const _ = require('lodash')
const db = require('../db')
const Book = require ('../models/Book')

function exists (book) {
  const { title, author, publisher } = book
  const sql = `select * from book where title = '${title}' and author='${author}' and publisher = '${publisher}'`
  return db.queryOne(sql)
}

async function removeBook (book) {
  if (book) {
    // 删除目录
    book.reset()
    // 删除数据库
    // if (book.fileName) {
    //   const removeBookSql = `delete from book where fileName = '${book.fileName}'`
    //   const removeContentsSql = `delete from content where fileName = '${book.fileName}'`
    //   await db.querySql(removeBookSql)
    //   await db.querySql(removeContentsSql)
    // }
  }
}

async function insertContents (book) {
  console.log('book', book)
  const contents = book.getContents()
  console.log('contents', contents)
  if (contents && contents.length > 0) {
    for(let i = 0; i < contents.length; i++) {
      const content = contents[i]
      const _content = _.pick(content, [
        'fileName',
        'id',
        'href',
        'order',
        'level',
        'label',
        'pid',
        'navId'
      ])
      // console.log('_content', _content)
      await db.insert(_content, 'contents')
    }
  }
}

function insertBook (book) {
  return new Promise(async (resolve, reject) => {
    try {
      if (book instanceof Book) {
        const result = await exists(book)
        if (result) {
          await removeBook(book)
          reject(new Error('电子已存在'))
        } else {
          await db.insert(book.toDb(), 'book')
          await insertContents(book)
          resolve()
        }
      } else {
        reject(new Error('添加图书对象不合法'))
      }
    } catch (e) {
      reject(e)
    }
  })
}

function getBook(fileName) {
  return new Promise(async (resolve, reject) => {
    const bookSql = `select * from book where fileName ='${fileName}'`
    const contentSql = `select * from contents where fileName='${fileName}' order by \`order\``
    const book = await db.queryOne(bookSql)
    const contents = await db.querySql(contentSql)
    if (book && contents.length) {
      resolve({ book, contents })
    } else {
      reject(new Error('查询图书不存在'))
    }

  })
}

function updateBook(book) {
  return new Promise(async (resolve, reject) => {
    try {
      // console.log('book--------', book instanceof Book)
      if (book instanceof Book) {
        const result = await getBook(book.fileName)
        // console.log('result--------', result)
        if (result) {
          const model = book.toDb()
          if (+result.updateType === 0) {
            reject(new Error('内置图书不能编辑'))
          } else {
            console.log('test1')
            const result = await db.update(model, 'book', `where fileName = '${book.fileName}'`)
            if (result) {
              resolve(result)
            } else {
              reject(result)
            }
          }
        }
      } else {
        console.log('失败')
      }
    } catch (e) {

    }
  })
}

async function getCategory() {
  const sql = 'select * from category order by category asc'
  const result = await db.querySql(sql)
  const categoryList = []
  result.forEach(item => {
    categoryList.push({
      label: item.categoryText,
      value: item.category,
      num: item.num
    })
  })
  return categoryList
}

async function listBook(query) {
  const {
    category = '',
    author = '',
    title = '',
    page = 1,
    sort,
    pageSize = 20
  } = query
  const offset = (page - 1) * pageSize
  let bookSql = 'select * from book'
  let where = 'where'
  category && ( where = db.and(where, 'category', category))
  author && ( where = db.andLike(where, 'author', author))
  title && ( where = db.andLike(where, 'title', title))
  if (where !== 'where') {
    bookSql = `${bookSql} ${where}`
  }
  if (sort) {
    const symbol = sort[0]
    const column = sort.slice(1, sort.length)
    const order = symbol === '+' ? 'asc' : 'desc'
    bookSql = `${bookSql} order by \`${column}\` ${order}`
  }
  let countSql = `select count(*) as count from book`
  if (where !== 'where') {
    countSql = `${countSql} ${where}`
  }
  const count = await db.querySql(countSql)
  bookSql = `${bookSql} limit ${pageSize} offset ${offset}`
  console.log(bookSql)
  const list = await db.querySql(bookSql)
  console.log(list)
  return {list, count: count[0].count, page, pageSize }
}

function deleteBook(fileName) {
  return new Promise(async (resolve, reject) => {
    let book = getBook(fileName)
    if (book) {
      if (+book.updateType === 0) {
        reject(new Error('内置电子书不能删除'))
      } else {
        const bookObject = new Book(null, book)
        const sql = `delete from book where fileName='${fileName}'`
        db.querySql(sql).then(() => {
          bookObject.reset()
          resolve()
        })
      }
    } else {
      reject(new Error('电子书不存在'))
    }
  })
}

module.exports = {
  insertBook,
  getBook,
  updateBook,
  getCategory,
  listBook,
  deleteBook
}
